#include <head.h>
void sys_error(const char *e)
{
    perror(e);
    exit(1);
}
void fn(char *p);
void sig_handler(int no)
{
    printf("child sig\n");
    waitpid(-1, NULL, 0);
}
int main(int argc, char **argv)
{
    int serversocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serversocket == -1)
    {
        sys_error("socket error");
    }
    struct sigaction act;
    act.sa_flags=0;
    act.sa_handler = sig_handler;
    sigemptyset(&act.sa_mask);
    sigaction(SIGCHLD,&act,NULL);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9000);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int r;
    // int r=  inet_pton(AF_INET,"127.0.0.1",&(addr.sin_addr.s_addr));
    // if(r ==0){
    //     sys_error("inet_pton");
    // }
    r = bind(serversocket, (struct sockaddr *)&addr, sizeof(addr));
    if (r == -1)
    {
        sys_error("bind");
    }
    listen(serversocket, 10);
    struct sockaddr_in client;
    socklen_t l = sizeof(client);
    int fd;
    while (1)
    {

        memset(&client, 0, sizeof(client));
again:
        fd = accept(serversocket, (struct sockaddr *)&client, &l);
        if (fd == -1)
        {
            if(errno == EINTR){
                goto again;
            }
            else{
                sys_error("accept error");
            }
        }
        pid_t pid = fork();
        if (pid == -1)
        {
            sys_error("fork error");
        }
        else if (pid > 0)
        {
            close(fd);
            continue;
        }
        else if (pid == 0)
        {
            close(serversocket);
            char buf[100];
            CLEAR_ARRAY(buf);
            printf("New connection from IP:%s,port:%d\n", inet_ntop(AF_INET, &(client.sin_addr), buf, sizeof(buf)), ntohs(client.sin_port));
            while (1)
            {
                CLEAR_ARRAY(buf);
                r = read(fd, buf, sizeof(buf));
                if (r == 0)
                {
                    printf("client disconnected\n");
                    close(fd);
                    break;
                }
                else if (r == -1)
                {
                    sys_error("read error");
                }
                printf("%s\n", buf);
                fn(buf);
                write(fd, buf, r);
            }
            return 0;
        }
    }
    return 0;
}
void fn(char *p)
{
    if (!p)
    {
        return;
    }
    while (*p)
    {
        *p = toupper(*p);
        p++;
    }
}
